package spring.my.db.sharding.demo.config.db.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:datasource.properties")
public class DruidSlave2DBConfig {

    private Logger logger = LoggerFactory.getLogger(DruidSlave2DBConfig.class);

    @Value("${spring.datasource.slave2.url:''}")
    private String dbUrl;

    @Value("${spring.datasource.slave2.username:''}")
    private String username;

    @Value("${spring.datasource.slave2.password:''}")
    private String password;

    @Value("${spring.datasource.slave2.driverClassName:''}")
    private String driverClassName;


    @Bean("dataSource2")     //声明其为Bean实例
    @Autowired
    public DataSource dataSource(DruidDataSource datasource) throws CloneNotSupportedException {
        DruidDataSource slaveDataSource = (DruidDataSource) datasource.clone();
        String blankString = "";
        if (!blankString.equals(dbUrl) && !blankString.equals(username) && !blankString.equals(password) && !blankString.equals(driverClassName)) {
            // 数据库地址
            slaveDataSource.setUrl(this.dbUrl);
            // 连接用户名
            slaveDataSource.setUsername(username);
            // 连接密码
            slaveDataSource.setPassword(password);
            // mysql驱动
            slaveDataSource.setDriverClassName(driverClassName);
        }
        return slaveDataSource;
    }
}
